package com.servlet;

import com.dao.MsgDao;
import com.dao.impl.MsgDaoImpl;
import com.entity.Msg;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MsgSerlvet extends HttpServlet {



    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        MsgDao msgDao = new MsgDaoImpl();
        //当前登录的用户名怎么拿到？？
       // req.getAttribute("loginuser");
        HttpSession session = req.getSession();
        req.setCharacterEncoding("utf-8");
        String action = req.getParameter("action");
        if("findMsg".equals(action)){
            String name = (String) session.getAttribute("loginuser");

            List<Msg> list = msgDao.findByLoginName(name);
            req.setAttribute("msgs",list);
            req.getRequestDispatcher("main.jsp").forward(req,resp);
        }else if("huixin".equals(action)){

           int id = Integer.parseInt(req.getParameter("msgid"));
            Msg msg = msgDao.findByMsgId(id);
            req.setAttribute("msg",msg);
            req.setAttribute("choose","huixin");
            req.getRequestDispatcher("newMsg.jsp").forward(req,resp);

        }else if("send".equals(action)){
            String sentTo = req.getParameter("toUser");
            String title = req.getParameter("title");
            String content = req.getParameter("content");
            String name = (String) session.getAttribute("loginuser");

            Msg msg = new Msg();
            msg.setMsgcontent(content);
            msg.setTitle(title);
            msg.setSendto(sentTo);
            msg.setUsername(name);
            int res = msgDao.addMsg(msg);
            if(res > 0){
                resp.sendRedirect("MsgSerlvet?action=findMsg");
            }else{
                req.setAttribute("error","发送失败");
                req.getRequestDispatcher("newMsg.jsp").forward(req,resp);
            }

        }


    }
}
